package Tree;

import java.util.Stack;

public class TreeNode {
    private TreeNode left;
    private TreeNode right;
    private char val;

    public TreeNode(char val) {
        this.val = val;
    }

    public TreeNode(TreeNode left,  char val,TreeNode right) {
        this.left = left;
        this.val = val;
        this.right = right;
    }

    //通过后缀表达式建树
    //21-3*
    public static TreeNode createSuffixExpressions(String s) {
        Stack<TreeNode> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '-', '+', '*', '/' -> {
                    TreeNode r = stack.pop();
                    TreeNode l = stack.pop();
                    TreeNode temp = new TreeNode(l,ch,r);
                    stack.push(temp);
                }
                default -> {
                    stack.push(new TreeNode(ch));
                }
            }

        }
        return stack.pop();
    }

    public void prevRecursion(TreeNode node) {
        if (node == null) {
            return;
        }
        prevRecursion(node.left);
        System.out.print(node.val + " ");
        prevRecursion(node.right);
    }

}
